<? 
require_once('../../models/Accounts.php'); 
require_once ('../../inc/functions.php');
require_once ('../../models/Users.php');
require_once ('../../models/ContactMethods.php');
?>

<!-- View -->
<!DOCTYPE html>
<html lang="en">
	<?php 
	include('../../inc/head.php'); 
	?>
	<body>
		<div>
			<?php include('../../inc/nav.php'); ?>
		</div>
		
		<div class="fb-login-button" data-show-faces="true" data-width="200" data-max-rows="1" data-scope="email,publish_stream">
		</div>
		<br />
		
		<?
			
			
			$userRow=Users::Blank();
			$contactRow=ContactMethods::Blank();
			
			$url = "https://graph.facebook.com/me?access_token=$_GET[access_token]";
			$results = curl_download($url);
			$ob = json_decode($results);
		?>
		

			<div id="content">
				<?
				$userID=null;
				$firstName=$ob->first_name;
				$lastName=$ob->last_name;
				$email=$ob->email;
				if (!isset($_SESSION['UserId']))
				{
					$userID=ContactMethods::EmailExists($email);
				}
				//$userID=ContactMethods::EmailExists($email);
				//(print_r("userID=".$userID));
				//(print_r("userID_session=".$_SESSION['UserId']));
				
				if ($firstName != null && $userID == null && $_SESSION['UserId'] == null)
				{	
					$userRow['FirstName']=$firstName;
					$userRow['LastName']=$lastName;
					$userRow['Keyword_id']=6;
					$_SESSION['UserId']=Users::Insert($userRow);
					
					$contactRow['Value']=$email;
					$contactRow['Keyword_id']=7;
					$contactRow['User_id']=$_SESSION['UserId'];
					$response=ContactMethods::Insert($contactRow);	
				}
				?>	
				<h3>Welcome <?=$firstName?> <?=$lastName?>!</h3>
				
			</div>

		
		
		<div id="fb-root"></div>
		<script>
		  window.fbAsyncInit = function() {
		  	    FB.init({
		  	    	      appId      : '528569337153435', // App ID from the App Dashboard
		  	    	            status: true, cookie: true, xfbml: true
		  	    	    });
		  	    	    
		  	    FB.getLoginStatus(function(response) {
		  	    		  if (response.status === 'connected') {
		  	    		  		     var uid = response.authResponse.userID;
		  	    		  		     var accessToken = response.authResponse.accessToken;
	    							<? if(!isset($_GET['access_token'])): ?>
		    						location = "?access_token=" + accessToken;
	    							<? endif; ?>
						  } else if (response.status === 'not_authorized') {
	    					// the user is logged in to Facebook, 
	   						// but has not authenticated your app
	  					  } else {
	    					// the user isn't logged in to Facebook.
	  					  }
	 			});
  			};

  			(function(d, debug){
     			var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
     			if (d.getElementById(id)) {return;}
     				js = d.createElement('script'); js.id = id; js.async = true;
     				js.src = "//connect.facebook.net/en_US/all" + (debug ? "/debug" : "") + ".js";
     				ref.parentNode.insertBefore(js, ref);
   				}(document, /*debug*/ false));
		</script>